package edu.ntu.cloudroid.server.backendservice.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CloudDroidCache<K, V> {
	class CacheItem<T> {
		private T value;

		public CacheItem(T value) {
			this.value = value;
		}

		public T getValue() {
			return value;
		}
	}

	public static final int SIZE = 100;
	private static final boolean enabled = true;

	private Map<K, CacheItem<V>> cache;
	private List<K> queue;
	private int size;

	public CloudDroidCache(int size) {
		if (enabled) {
			this.size = size;
			this.cache = new HashMap<K, CacheItem<V>>(size);
			this.queue = new ArrayList<K>(size);
		}
	}

	public synchronized void update(K key, V value) {
		if (!enabled) return;

		delete(key);
		put(key, value);
	}

	public synchronized void put(K key, V value) {
		if (!enabled) return;
		if (size < cache.size()) {
			cache.remove(queue.remove(0));
		}

		CacheItem<V> ci = new CacheItem<V>(value);
		cache.put(key, ci);
		queue.add(key);
	}

	public synchronized V get(K key) {
		if (!enabled) return null;
		CacheItem<V> ci = cache.get(key);

		if (null != ci) {
			queue.remove(key);
			queue.add(key);
			return ci.getValue();
		} else
			return null;	
	}

	public synchronized void delete(K key) {
		if (!enabled) return;

		queue.remove(key);
		cache.remove(key);
	}
}
